#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "Err.hpp"

class Sock
{
public:
    const static int backlog = 32;
    const static int defaultSock = -1;

public:
    Sock(int sock = defaultSock)
        : _listensock(sock)
    {
    }
    void Socket()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            logMessage(FATAL, "create socket error");
            exit(SOCKET_ERR);
        }
        logMessage(NORMAL, "create socket success: %d", _listensock);
        // 下面这两行代码是让一个失效的port能够立即再被使用 ，bind err
        int opt = 1;
        setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
    }

    void Bind(uint16_t port)
    {
        //    int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        // client.sin_addr.s_addr = inet_addr(clientip.c_str());
        local.sin_addr.s_addr = INADDR_ANY; // 绑定的端口类似与"0.0.0.0"
        socklen_t len = sizeof local;
        if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind socket error");
            exit(BIND_ERR);
        }
        logMessage(NORMAL, "bind socket success");
    }

    void Listen()
    {
        if (listen(_listensock, backlog) < 0)
        {
            logMessage(FATAL, "listen socket error");
            exit(LISTEN_ERR);
        }
        logMessage(NORMAL, "listen socket success");
    }

    int Accept(std::string *clientip, uint16_t *clientport,int* err)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof peer;
        int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
        if (_listensock < 0)
        {
            logMessage(FATAL, "accept socket error");
            exit(SOCKET_ERR);
        }
        else
        {
            *clientip = inet_ntoa(peer.sin_addr);
            *clientport = ntohs(peer.sin_port);
        }
        return sock;
        
    }

    int getFd()
    {
        return _listensock;
    }
    void Close()
    {
        if(_listensock != defaultSock) close(_listensock);
    }

    ~Sock()
    {
    }

private:
    int _listensock;
};